angular.module('ionicApp', ['ionic'])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.withCredentials = true;
    }])
    .config(function($stateProvider, $urlRouterProvider) {

        $stateProvider
            .state('tabs', {
                url: '/card',
                abstract: true,
                templateUrl: 'templates/tabs.html'
            })
            .state('tabs.card', {
                url: '/list',
                views: {
                    'card-tab': {
                        templateUrl: 'templates/card_list.html',
                        controller: 'cardListCtrl'
                    }
                }
            })
            .state('tabs.index', {
                url: '/index',
                views: {
                    'card-tab': {
                        templateUrl: 'templates/index.html',
                        controller:"indexCtrl"
                    }
                }
            })
            .state('tabs.changePassword', {
                url: '/changePassword',
                views: {
                    'card-tab': {
                        templateUrl: 'templates/changePassword.html',
                        controller:"changePasswordCtrl"
                    }
                }
            })
            .state('tabs.home', {
                url: '/home',
                views: {
                    'card-tab': {
                        templateUrl: 'templates/home.html',
                        controller: 'HomeTabCtrl'
                    }
                }
            })
            .state('tabs.history', {
                url: '/history/:card_id',
                views: {
                    'card-tab': {
                        templateUrl: 'templates/record.html',
                        controller: 'cardHistoryCtrl'
                    }
                }
            })
            .state('tabs.consume', {
                url: '/consume/:_id',
                views: {
                    'card-tab': {
                        templateUrl: 'templates/consume.html',
                        controller: 'cardRechargeCtrl'
                    }
                }
            })
            .state('tabs.setup', {
                url: '/setup/:_id',
                views: {
                    'card-tab': {
                        templateUrl: 'templates/setup.html',
                        controller: 'cardRechargeCtrl'
                    }
                }
            })
            .state('tabs.recharge', {
                url: '/recharge/:_id',
                views: {
                    'card-tab': {
                        templateUrl: 'templates/recharge.html',
                        controller: 'cardRechargeCtrl'
                    }
                }
            });
        $urlRouterProvider.otherwise('/card/home');

    })

    .controller('SignInCtrl', function($scope, $state) {

        $scope.signIn = function(user) {
            console.log('Sign-In', user);
            $state.go('tabs.home');
        };

    })
    .factory('cardService', ['$http', '$location','$rootScope', function ($http, $location,$rootScope) {
        return {
            list: function (limit, page, app_id, fn) {
                var param = {
                    limit: limit,
                    page: page
                };

                baas_yl.call({
                    'http': $http,
                    'method': 'get',
                    'uri': 'card/index/list',
                    'data': param,
                    'success': function (d) {
                        if (typeof fn == 'function') {
                            fn(d);
                        }
                    }
                });
            },
            bindMember : function( _id, app_id, person, recall ){
                var data = {
                    name : person.name,
                    phone:person.phone,
                    cardid:person.cardid
                };
                baas_yl.call({
                    'http': $http,
                    'method': 'post',
                    'uri': 'card/index/' + _id + '/bindElder',
                    'data':data,
                    'success': function(d) {
                        if (d.status == '1') {
                            if (typeof recall == 'function') {
                                recall(d);
                            }
                        }else{
                            if( d.description ){
                                alert(d.description );
                            }else{
                                alert( '网络原因，请求失败，请稍后重试' );
                            }
                        }
                    }
                });
            },
            edit : function( _id, app_id, params, recall ){
                var data = { };
                if( typeof params.member != 'undefined' ){
                    data.member = params.member;
                }
                if( typeof params.status != 'undefined' ){
                    data.status = params.status;
                }

                baas_yl.call({
                    'http': $http,
                    'method': 'post',
                    'uri': 'card/index/update/' + _id,
                    'data':data,
                    'success': function(d) {
                        if(d.status == '1'){
                            if( typeof recall == 'function'){
                                recall( d );
                            }
                        }else{
                            if( d.description ){
                                alert(d.description );
                            }else{
                                alert( '网络原因，请求失败，请稍后重试' );
                            }
                        }
                    }
                });
            },
            find_one : function( _id, app_id, fn ){
                baas_yl.call({
                    'http': $http,
                    'method': 'get',
                    'uri': 'card/index/elderid/' + _id,
                    'success': function(d) {
                        if (typeof fn == 'function') {
                            fn(d);
                        }
                    }
                });
            },
            changeStatus : function( _id, app_id,status, fn ){
                var data = {
                    status : status
                };
                baas_yl.call({
                    'http': $http,
                    'method': 'post',
                    'uri': 'card/index/changeStatus/' + _id,
                    'data' : data,
                    'success': function(d) {
                        if (typeof fn == 'function') {
                            fn(d);
                        }
                    }
                });
            },
            add : function(manageId, app_id, data, fn ){
                var data = {
                    number : data.number,
                    fund   : data.fund,
                    rule   : data.rule,
                    type   : data.type,
                    manageId :manageId
                };
                baas_yl.call({
                    'http': $http,
                    'method': 'post',
                    'uri': 'card/index/create',
                    'data' : data,
                    'success': function(d) {
                        if(d.status == '1'){
                            if( typeof fn == 'function'){
                                fn( d );
                            }
                        }else{
                            if( d.description ){
                                alert(d.description );
                            }else{
                                alert( '网络原因，请求失败，请稍后重试' );
                            }
                        }
                    }
                });
            },
            searchCard : function( data,limit, page,app_id, fn ){
                var param = {
                    limit:limit,
                    page:page,
                    card_id : (data.card_id != undefined)?data.card_id:'',
                    name : (data.name != undefined)?data.name:'',
                    phone : (data.phone != undefined)?data.phone:'',
                    em_name : (data.em_name != undefined)?data.em_name:'',
                    em_phone   : (data.em_phone != undefined)?data.em_phone:''
                };
                baas_yl.call({
                    'http': $http,
                    'method': 'post',
                    'uri': 'card/index/searchCard',
                    'data' : param,
                    'success': function(d) {
                        if( typeof fn == 'function'){
                            fn( d );
                        }
                    }
                });
            },
            history : function( card_id,app_id, fn ){
                baas_yl.call({
                    'http': $http,
                    'method': 'get',
                    'uri': 'card/index/history/'+ card_id,
                    'success': function(d) {
                        if( typeof fn == 'function'){
                            fn( d );
                        }
                    }
                });
            },
            transaction : function( data, card_id, app_id, fn ){
                var data = {
                    type : data.type,
                    fund : data.fund,
                    description : data.description,
                    status : data.status,
                    shop : data.type=="pay"?"到店消费":""
                };
                baas_yl.call({
                    'http': $http,
                    'method': 'post',
                    'uri': 'card/index/transaction/' + card_id,
                    'data' : data,
                    'success': function(d) {
                        if( typeof fn == 'function'){
                            fn( d );
                        }
                    }
                });
            },
            information : function( transaction_no, app_id, fn ){
                baas_yl.call({
                    'http': $http,
                    'method': 'get',
                    'uri': 'card/index/information/' + transaction_no,
                    'success': function(d) {
                        if( typeof fn == 'function'){
                            fn( d );
                        }
                    }
                });
            },
            check_trans : function( type, transaction_id, app_id, fn ){
                if( type != 'charge' && type!= 'pay' ){
                    alert('交易类型错误');
                    return;
                }
                var data = {
                    type : type
                };
                baas_yl.call({
                    'http': $http,
                    'method': 'post',
                    'uri': 'card/index/'+ type + '/' + transaction_id,
                    'data' : data,
                    'success': function(d) {
                        if( typeof fn == 'function'){
                            fn( d );
                        }
                    }
                });
            },
            typeList : function( app_id, fn ){
                baas_yl.call({
                    'http': $http,
                    'method': 'get',
                    'uri': 'card/index/typeList',
                    'success': function(d) {
                        if( typeof fn == 'function'){
                            fn( d );
                        }
                    }
                });
            },
            delType : function( data,app_id, fn ){
                var data = {
                    name : data.name
                };
                baas_yl.call({
                    'http': $http,
                    'method': 'post',
                    'uri': 'card/index/delType',
                    'data' : data,
                    'success': function(d) {
                        if( typeof fn == 'function'){
                            fn( d );
                        }
                    }
                });
            },
            find_type : function( code,app_id, fn ){
                baas_yl.call({
                    'http': $http,
                    'method': 'get',
                    'uri': 'card/index/findType/' + code,
                    'success': function(d) {
                        if( typeof fn == 'function'){
                            fn( d );
                        }
                    }
                });
            },
            createType : function( code,app_id, data, fn ){
                var data = {
                    name : data.name,
                    code : code
                };
                baas_yl.call({
                    'http': $http,
                    'method': 'post',
                    'uri': 'card/index/createType',
                    'data' : data,
                    'success': function(d) {
                        if(d.status == '1'){
                            if( typeof fn == 'function'){
                                fn( d );
                            }
                        }else{
                            if( d.description ){
                                alert(d.description );
                            }else{
                                alert( '网络原因，请求失败，请稍后重试' );
                            }
                        }
                    }
                });
            },
            searchArchives : function(member,app_id,fn){
                var params ={
                    cardid: ( member.cardid !='' && member.cardid != undefined) ? member.cardid : undefined
                };
                baas_yl.call({
                    'http' : $http,
                    'method' : 'get',
                    'uri' : 'archives/archives/list',
                    'data' : params,
                    'success' : function(d){
                        if(typeof fn == 'function'){
                            fn(d);
                        }
                    }
                });
            },
            checkLogin : function(type){
                $rootScope.manager = {};
                baas_yl.call({
                    'http': $http,
                    'method': 'get',
                    'uri': 'manager/manager/checkLogin',
                    'success': function(d) {
                        if(d.login!='logged'){
                            $location.path("/card/home");
                        }else if(d.managerGroup == null || d.managerGroup.groupName != 'dianzhang'){
                            alert('您不是店长,请用店长账户登陆');
                            $location.path("/card/home");
                        }else{
                            if(type == "first"){
                                $rootScope.manager = d;
                                $rootScope.manager.account= d.manager_account;
                                var rules=d.managerGroup.groupName;
                                if(rules=="admin"){
                                    $location.path("/card/index");
                                }else if(rules=="allTest"){
                                    $location.path("/card/index");
                                }else{
                                    $location.path("/card/index");
                                }
                            }
                        }


                    }
                });

            },
            loginout : function(){
                baas_yl.call({
                    'http': $http,
                    'method': 'post',
                    'uri': 'manager/manager/logout',
                    'success': function(d) {

                        if(d.login!='logged'){
                            $location.path("card/home");
                        }
                    }
                });
            }
        }
    }])



    .controller('indexCtrl',function($location,  $scope, $state,$stateParams ,$timeout, $http,cardService){
        $scope.loginout = function(){
            cardService.loginout();
        };
    })
    .controller('changePasswordCtrl',function($location,  $scope, $state,$stateParams ,$timeout,$http,$rootScope, cardService){
        $scope.manager = $rootScope.manager;

        $scope.changePassword = function () {

            if($scope.manager.password==""){
                alert("请输入原始密码");
                return;
            }
            if($scope.manager.new_password==""){
                alert("请输入新密码");
                return;
            }
            if($scope.manager.qnew_password==""){
                alert("请输入确认密码");
                return;
            }
            if($scope.manager.qnew_password != $scope.manager.new_password){
                alert("新密码与确认密码不相同");
                return;
            }


            var data = {
                account      : $scope.manager.manager_account,
                password     : $scope.manager.password,
                new_password : $scope.manager.new_password
            };

            baas_yl.call({
                'http': $http,
                'method': 'post',
                'uri': 'manager/manager/changePassword',
                'data' : data,
                'success': function(d) {
                    if(d.status == '1'){
                        alert("密码已修改，请重新登录!");
                        cardService.loginout();
                    }else{
                        if( d.description ){
                            alert("原始密码输入错误");
                        }else{
                            alert( '网络原因，请求失败，请稍后重试' );
                        }

                    }
                }
            });

        };
        $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
            dropdown();
        })
    })
    .controller('cardListCtrl', function($location,  $scope, $state,$stateParams ,$timeout, cardService) {
        cardService.checkLogin();

        $scope.app_id = $stateParams.app_id;
        /*分页*/
        $scope.selectedPage = 1;
        $scope.data = {
            selectedPage  : $scope.selectedPage,
            page : $scope.page
        };
        $scope.limit = 20;
        $scope.getList = function( ){
            cardService.list( $scope.limit,$scope.selectedPage,$scope.app_id, function( json ){

            });
        };
        $scope.searchCard = function(data ){
            $scope.selectedPage = 1;
            $scope.limit = 20;
            cardService.searchCard( data,$scope.limit, $scope.selectedPage,$scope.app_id, function( json ){
                if(json != ""){
                    $scope.notFundAnyMember = 0 ;
                    $scope.list = json;
                    $scope.count = json.count;
                    $scope.currentPage = 1;
                    $scope.getPage(json.count);
                }else{
                    $scope.notFundAnyMember = 1 ;
                }

            });
        };
        $scope.getList();
        $scope.edit = function(){

        }

        /*分页*/
        $scope.changePage = function( p ){
            $scope.data.selectedPage = p;
            cardService.list( $scope.limit,p,$scope.app_id, function( json ){
                $scope.list = json.list;
                $scope.count =  json.count;
                $scope.currentPage = p ;
                $scope.getPage(json.count);
            });
        };
        $scope.getPage = function(count){
            $scope.pageList = [];
            var limit = 20;//返回的条数
            $scope.totalPage = parseInt(count / limit);//总页数
            $scope.totalPage += count % limit >= 1 ? 1 : 0;//判断页数是否是整数
            var start = ( $scope.currentPage - 2 ) >= 1 ? $scope.currentPage - 2 : 1;//首页
            var end = ( $scope.currentPage + 2 ) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage;//尾页

            $scope.frontdotShow = start > 1 ? true : false;//前面的省略号
            $scope.backdotShow = end < $scope.totalPage ? true : false;//后面的省略号
            for(var i = start; i <= end; i ++){
                $scope.pageList.push({
                    number : i,
                    active : i== $scope.currentPage ? 'active':''
                });//给点击的按钮添加class
            }

        };
    })
    .controller('cardRechargeCtrl', function($window,$location,$scope,$state, $http, $stateParams, $timeout,cardService ) {
        cardService.checkLogin();
        $scope.isPaying = false;

        $scope._id = $stateParams._id;
        $scope.app_id = $stateParams.app_id;

        $scope.find_one = function(  ){
            cardService.find_one( $scope._id, $scope.app_id,  function( json ){
                $scope.card = json;
                if( typeof $scope.card.member != 'undefined' && $scope.card.member != '' ){
                    $scope.card.bind = 1;
                }else{
                    $scope.card.bind = 0;
                }
            } );
        };
        $scope.find_one();

        $scope.member = {};
        $scope.searchMember = function(){
            $timeout(function(){
                $http.get( url ).success(function( json ){
                    $scope.member.findAll = json;
                });

                baas_yl.call({
                    'http': $http,
                    'method': 'get',
                    'uri': 'card/elder/search/'+ $scope.member.search + '?app_id=' + $scope.app_id,
                    'success': function(d) {
                        $scope.member.findAll = json;
                    }
                });
            },200);
        };

        //根据身份证搜索老人信息
        $scope.searchArchives = function(){
            cardService.searchArchives($scope.member, $scope.app_id,function(json){
                $scope.member = json['list'][0];
                console.log(json['list']);
            });
        }

        $scope.dispatchCard = function( person ){
            //var member_id = person._id;
            cardService.bindMember( $scope._id, $scope.app_id, person, function( json ){
                $scope.find_one();
                alert("绑定老人信息成功！");
                var manageName = $scope.manager.manager_account
                if( manageName =='admin'){
                    $location.path( '/card' );
                }else{

                    $location.path( '/card/index' );
                }

            });
        };
        //更改会员卡状态
        $scope.changeStatus = function(card){
            var status = card.status;
            cardService.changeStatus( $scope._id, $scope.app_id, status, function( json ){
                $scope.find_one();
                alert("会员卡状态更新完成！");
                var manageName = $scope.manager.manager_account
                if( manageName =='admin'){
                    $location.path( '/card' );
                }else{
                    $location.path( '/card/index' );
                }
            });

        };
        $scope.pay = function( card , type){
            $scope.isPaying = true;

            if(card.description == "" || typeof card.description == "undefined"){
                alert("请填写扣款备注！");
                $scope.isPaying = false;
                return false;
            }
            var data = {
                type : type,
                fund : type == 'charge' ? card.charge_number : card.pay_number ,
                description : card.description,
                status : card.status
            };
            if( isNaN( data.fund ) || data.fund < 1 ){
                alert('请填写正整数');
                $scope.isPaying = false;
                return;
            }
            cardService.transaction( data, card.card_id, $scope.app_id, function( json ){

                if( json.status ){
                    cardService.check_trans( 'charge', json.transaction_no, $scope.app_id, function(){
                        alert('交易成功');
                        $location.path('/card/list');
                    });
                }
                else{
                    alert(json.description);
                    $scope.isPaying = false;
                }
            });

        };

    })
    .controller('HomeTabCtrl', function($window,$location,$scope,$state, $http ,cardService)  {

        $scope.login = function(){

            var data = {
                'account'  : $('#account').val(),
                'password' : $('#password').val()
            };
            baas_yl.call({
                'http': $http,
                'method': 'post',
                'data':data,
                'uri': 'manager/manager/login',
                'success': function(d) {
                    if (d.status == 1) {
                        cardService.checkLogin('first');
                    } else {
                        alert("账户或密码错误");
                    }
                }
            });
        };
    })
    .controller('cardHistoryCtrl',function($window,$location,$scope,$state, $http, $stateParams, $timeout,cardService){
        $scope.app_id = $stateParams.app_id;
        $scope.card_id = $stateParams.card_id;
        $scope.history = function( ){

            cardService.history( $scope.card_id,$scope.app_id, function( json ){
                $scope.list = json.list;
                console.log($scope.list);

                for(var m = 0, i = $scope.list.length - 1; i >= 0; i--){
                    if($scope.list[i].type == "pay"){
                        m += parseFloat($scope.list[i].fund);
                    }
                    if(m >= 120){
                        $scope.mark = i;
                        break;
                    }
                }

            });
        };
        $scope.history();
    })